package com.chenyaowei.happyhub.service;

import com.chenyaowei.happyhub.mapper.AdminMapper;
import com.chenyaowei.happyhub.pojo.Admin;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private CaptchaService captchaService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin =adminMapper.selectAdminByUsername(username);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String password=request.getParameter("password");
        String ticket=request.getParameter("ticket");
        String randStr=request.getParameter("randStr");
        if(!captchaService.VerifyTicket(ticket,randStr))
            throw new BadCredentialsException("验证失败,请重新登录");
        if(admin==null)
            throw new BadCredentialsException("帐号不存在，请重新输入");
        if(!admin.getPassword().equals(password)) {
            System.out.println("密码错误");
            throw new BadCredentialsException("密码错误，请重新输入");
        }
        System.out.println("return user");
        return new User(admin.getUsername(),new BCryptPasswordEncoder().encode(admin.getPassword()), AuthorityUtils.createAuthorityList(admin.getRole()));
    }
}
